package com.jeesite.modules.wx.miniapp.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.jeesite.common.config.Global;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.utils.IdcardUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.bis.entity.BisUser;
import com.jeesite.modules.bis.service.BisUserService;
import com.jeesite.modules.utils.PhoneUtils;
import com.jeesite.modules.wx.miniapp.config.WxMaConfiguration;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@RequestMapping("/wx/user/{appid}")
public class WxMaUserController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BisUserService bisUserService;

    /**
     * 登陆接口
     */
    @PostMapping("/login")
    public String login(@PathVariable String appid, String code) {
        if (StringUtils.isBlank(code)) {
            return renderResult(Global.FALSE, "非法访问");
        }
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            BisUser param = new BisUser();
            param.setOpenid(session.getOpenid());
            BisUser bisUser = bisUserService.getByOpenId(param);
            if (bisUser != null){
                bisUser.setSessionId(session.getSessionKey());
                bisUserService.save(bisUser);
                return renderResult(Global.TRUE, "isLogon", bisUser);
            } else {
                bisUser = new BisUser();
                bisUser.setSessionId(session.getSessionKey());
                bisUser.setOpenid(session.getOpenid());
                return renderResult(Global.TRUE, "needLogin", bisUser);
            }

        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return renderResult(Global.FALSE, "登陆失败，原因：" + e.getMessage());
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @PostMapping("/info")
    public String info(@PathVariable String appid, String sessionKey, String signature, String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return renderResult(Global.FALSE, "非法访问");
        }
        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        BisUser bisUser = new BisUser();
        bisUser.setOpenid(userInfo.getOpenId());
        bisUser.setSessionId(sessionKey);
        bisUser.setName(userInfo.getNickName());
        bisUser.setLanguage(userInfo.getLanguage());
        bisUser.setCountry(userInfo.getCountry());
        bisUser.setProvince(userInfo.getProvince());
        bisUser.setCity(userInfo.getCity());
        bisUser.setNickName(userInfo.getNickName());
        bisUser.setHeadImageUrl(userInfo.getAvatarUrl());
        bisUser.setSex(Long.parseLong(userInfo.getGender()));
        bisUser.setStatus("0");
        bisUserService.save(bisUser);
        return renderResult(Global.TRUE, "成功", bisUser);
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @PostMapping("/auth")
    public String auth(String sessionKey, String name, String mobilePhone, String idCard) {
        if (StringUtils.isBlank(name)) {
            return renderResult(Global.FALSE, "请填写姓名");
        }
        if (StringUtils.isBlank(mobilePhone)) {
            return renderResult(Global.FALSE, "未填写手机号码");
        }
        if (!PhoneUtils.isMobileNO(mobilePhone)) {
            return renderResult(Global.FALSE, "手机号码填写错误");
        }
        if (StringUtils.isBlank(idCard)) {
            return renderResult(Global.FALSE, "请填写身份证");
        }
        if (!IdcardUtils.validateIdCard18(idCard)) {
            return renderResult(Global.FALSE, "身份证填写错误");
        }
        BisUser bisUser = bisUserService.getBySessionKey(sessionKey);
        if (bisUser != null) {
            bisUser.setName(name);
            bisUser.setMobilePhone(mobilePhone);
            bisUser.setIdCard(idCard);
            bisUserService.save(bisUser);
            return renderResult(Global.TRUE, "成功", bisUser);
        }
        return renderResult(Global.FALSE, "没有找到用户");
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public String phone(@PathVariable String appid, String sessionKey, String signature, String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

//        return JsonUtils.toJson(phoneNoInfo);
        return renderResult(Global.TRUE, "成功", phoneNoInfo);
    }

}
